package org.vt.ece4564.pcw.assignment2;

import java.io.IOException;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.jdo.Query;

import javax.servlet.ServletConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.vt.ece4564.pcw.assignment2data.Contact;

@SuppressWarnings("serial")
public class TextInClassGetContacts extends HttpServlet {
	
	@Override
	public void init(ServletConfig servletConfig) {
		
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		response.setContentType("text/xml");
		
		String responseXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
		responseXML += "<contacts>\n";
		
		List<Cookie> cookies = Arrays.asList(request.getCookies());
		String username = "";
		
		for (Cookie c : cookies) {
			String name = c.getName();
			String value = c.getValue();
			
			if (name.equals("loggedIn")) {
				String[] values = value.split(":");
				Date currentDate = new Date();
				long cookieExpiration = Long.valueOf(values[1]).longValue();
				
				if (currentDate.getTime() > cookieExpiration) {
					response.getWriter().write("Error: Expired Cookie");
					return;
				}
				
				username = values[0];
				break;
			}
		}
		
		if (username.equals("")) {
			response.getWriter().write("Error: Invalid Cookie");
			return;
		}
		
		Query query = PMF.get().getPersistenceManager().newQuery("select from " +
				Contact.class.getName() + " where username_==user");
		query.declareParameters("String user");
		
		@SuppressWarnings("unchecked")
		List<Contact> contacts = (List<Contact>) query.execute(username);
		
		for (Contact c : contacts) {
			responseXML += "\t<contact>\n\t\t<name>" + c.getName() + "</name>\n";
			responseXML += "\t\t<number>" + c.getNumber() + "</number>\n";
			responseXML += "\t</contact>";
		}
		
		responseXML += "</contacts>";
		response.getWriter().write(responseXML);
	}
}
